//
//  PlayerViewController.m
//  NewChat
//
//  Created by 马欢 on 16/3/6.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "PlayerViewController.h"
#import "MHDataHelper.h"
#import "PlayerManager.h"
#import "MusicListCell.h"
#import "UIImageView+WebCache.h"
#import "NSString+TimeFormatter.h"

#define Manager [PlayerManager defaultManager]
static NSString *playMode = @"xunhuan";//初始播放模式为循环播放
static NSInteger i = 0;

@interface PlayerViewController ()<UITableViewDataSource,UITableViewDelegate,PlayerMangerDelegate>
@property (nonatomic,strong)UIImageView *backgroundView;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;//下一首
@property (weak, nonatomic) IBOutlet UIButton *lastBtn;//上一首
@property (weak, nonatomic) IBOutlet UIButton *nextListBtn;//换一批
@property (weak, nonatomic) IBOutlet UIButton *playAndPauseBtn;//暂停
@property (weak, nonatomic) IBOutlet UIButton *mode;//播放模式
@property (weak, nonatomic) IBOutlet UISlider *slider;//快进
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;//当前时间
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;//歌曲总时长

@property (nonatomic,strong)NSMutableArray *guessArray;
@property (nonatomic,strong)NSMutableArray *allLikeArray;


@end

@implementation PlayerViewController

//类方法，单例对象(该单例比较特殊，记得回顾)
+(instancetype)sharedPlayerViewController{
    static PlayerViewController *playerVC = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[PlayerViewController alloc]init];
    });
    return playerVC;
}
//加载视图
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addViews];

}

//=============待 修改 添加=================
//切歌（代理）
-(void)didSkippedSong:(SongModel *)song{
    //初始化controlView上的子控件
    [self.playAndPauseV sd_setImageWithURL:[NSURL URLWithString:song.picUrl] placeholderImage:nil];
    [self preparesubViewsInitStatus:song];
    //    获取title
    self.navigationItem.title = [NSString stringWithFormat:@"%@",song.name];
//    待决定是否删========
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:Manager.currentIndex inSection:0];
    [self.MusicListTV selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionNone)];
}

//换一批
-(void)nextList{
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    if (status == RealStatusNotReachable){//无网
        
    }else{//有网
    if (i == 0) {
        [[MHDataHelper shareDataHelper] requestAllSongsWithGuess:guess didFinished:^(NSMutableArray *array) {
            Manager.passModels = array;
            [self.MusicListTV reloadData];
            i = 1;
        }];
    }else if(i == 1){
        [[MHDataHelper shareDataHelper] requestAllSongsWithAllLike:AllLike didFinished:^(NSMutableArray *array) {
            Manager.passModels = array;
            [self.MusicListTV reloadData];
            i = 0;
        }];
    }
 }
}

//==================问题多 经常改=======================

//关播放器 退出
-(void)stopAction{
    [Manager stopPlay];
    [self.playAndPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
    [self backAction];
    
}
//=======================一般不改=========================
-(void)viewWillAppear:(BOOL)animated{
    [self.tabBarController.tabBar setHidden:YES];
    
    
    if([MHDataHelper shareDataHelper].allSongsArray.count > 0)
    {
        Manager.passModels = [MHDataHelper shareDataHelper].allSongsArray;
        if (Manager.currentIndex == -1) {
            [Manager prepareMusicWithIndex:0];
        }
    }
    
        if ([PlayerManager defaultManager].player.rate == 0) {
            [self.playAndPauseBtn setImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
        }
}


//退出
-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


//播放模式切换
- (IBAction)playMode:(id)sender {
    if ([playMode isEqualToString:@"xunhuan"]) {
        [self.mode setImage:[UIImage imageNamed:@"danqu"] forState:(UIControlStateNormal)];
        playMode = @"danqu";
        
    }else if ([playMode isEqualToString:@"danqu"]){
        [self.mode setImage:[UIImage imageNamed:@"suiji"] forState:(UIControlStateNormal)];
        playMode = @"suiji";
    }else{
        [self.mode setImage:[UIImage imageNamed:@"xunhuan"] forState:(UIControlStateNormal)];
        playMode = @"xunhuan";
    }
    Manager.playMode = playMode;
}
//播放/暂停
-(void)playAndPause{
    if ([PlayerManager defaultManager].player.rate != 0) {
        [[PlayerManager defaultManager] pausePlay];
        [self.playAndPauseBtn setImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
    }else{
        [[PlayerManager defaultManager] musicPlay];
        [self.playAndPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
    }
}
//上一首
-(void)lastMusic{
    [Manager lastMusic];
}
//下一首
-(void)nextMusic{
    [Manager nextMusic];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return Manager.passModels.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}
-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//加载视图
-(void)addViews{
    //加背景图片
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.backgroundView.image = [UIImage imageNamed:@"100.jpg"];
    [self.view addSubview:self.backgroundView];
    //    //  创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //  毛玻璃view 视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //添加到要有毛玻璃特效的控件中
    effectView.frame = self.backgroundView.bounds;
    //设置模糊透明度（范围0到1）
    effectView.alpha = 0.6f;
    [self.backgroundView addSubview:effectView];
    [self.view sendSubviewToBack:self.backgroundView];
    
    self.title = @"音乐电台";//标题
    self.edgesForExtendedLayout = UIRectEdgeAll;//距离四周边距
    self.playAndPauseV.layer.masksToBounds = YES;//变圆
    self.playAndPauseV.layer.cornerRadius = self.playAndPauseV.frame.size.width/2.0;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"个人中心" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"退出电台" style:(UIBarButtonItemStylePlain) target:self action:@selector(stopAction)];
    //    button添加事件
    [self.lastBtn addTarget:self action:@selector(lastMusic) forControlEvents:(UIControlEventTouchUpInside)];
    [self.nextBtn addTarget:self action:@selector(nextMusic) forControlEvents:(UIControlEventTouchUpInside)];
    [self.playAndPauseBtn addTarget:self action:@selector(playAndPause) forControlEvents:(UIControlEventTouchUpInside)];
    [self.nextListBtn addTarget:self action:@selector(nextList) forControlEvents:(UIControlEventTouchUpInside)];
    //    注册cell
    UINib *nib = [UINib nibWithNibName:@"MusicListCell" bundle:nil];
    [self.MusicListTV registerNib:nib forCellReuseIdentifier:@"listCell"];
    //    设置tableview代理
    self.MusicListTV.dataSource = self;
    self.MusicListTV.delegate = self;
    
    Manager.didSkippedSongDelegate = self;
    
}
//设置cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //   换自定义cell！！！！！！
    MusicListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
    if (Manager.passModels.count) {
        cell.song = Manager.passModels[indexPath.row];
    }
    cell.number.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    cell.number.textColor = [UIColor purpleColor];
    cell.singerLabel.textColor = [UIColor purpleColor];
    cell.musicNameLabel.textColor = [UIColor purpleColor];
    
    cell.Picture.layer.masksToBounds = YES;
    cell.Picture.layer.cornerRadius = cell.Picture.frame.size.width/2.0;
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:230/255.0 green:200/255.0 blue:50/255.0 alpha:1];
    
    return cell;
}
//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [Manager prepareMusicWithIndex:indexPath.row];
}
//切歌后 初始显示设置
-(void)preparesubViewsInitStatus:(SongModel *)song{
    self.flag = YES;
    //    初始化控件
    self.currentTimeLabel.text = @"00:00";
    
    int seconds =  [[song.urlList[1] valueForKey:@"duration"] intValue]/1000;
    self.endTimeLabel.text = [NSString getStringFormateByTime:seconds];
    //int 比 float 占用内存小 可以不用强转
    
    //    设置slider的最大值
    self.slider.maximumValue = seconds;
    
    [self.slider addTarget:self action:@selector(didClickTimeSliderTouchUpInside:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.slider addTarget:self action:@selector(didClickTimeSliderTouchUpInside:) forControlEvents:(UIControlEventTouchUpOutside)];
    
    [self.slider addTarget:self action:@selector(didClickTimeSliderTouchDown:) forControlEvents:(UIControlEventTouchDown)];
}
//用ValueChanged有个问题，滑动时候不放歌了，所以用TouchUpInside和TouchDown并判断
//滑动播放时间Slider，具体分析见下面changeTimeSliderAndCurrentLabe方法实现
-(void)didClickTimeSliderTouchUpInside:(UISlider *)slider{
    [[PlayerManager defaultManager] musicSeekToTime:slider.value];
    _flag = YES;
}
-(void)didClickTimeSliderTouchDown:(UISlider *)slider{
    _flag = NO;
}


//根据时间字符串来设置timeSlider和currentTimeLabel
-(void)changeTimeSliderAndCurrentLabelWithTimeString:(NSString *)string{
    //获取秒数 通过 时间字符串
    self.currentTimeLabel.text = string;
    if (_flag) {//flag为YES 执行下面这句，slider随播放时间动，当滑动slider时，为NO，slider不随播放时间动，可以自由滑动slider,实际播放时间也正常，只有松手时，实际播放时间才变
        self.slider.value = [string getSecondsFomatByTimeString];
    }
}
//正在播放 代理
-(void)isPlayingMusicAsTime:(NSString *)timeString{
    //musicPic旋转起来
    self.playAndPauseV.transform = CGAffineTransformRotate(self.playAndPauseV.transform, M_PI/180.0);
    [self changeTimeSliderAndCurrentLabelWithTimeString:timeString];
}
//懒加载
-(NSMutableArray *)allLikeArray{
    if (!_allLikeArray) {
        _allLikeArray = [NSMutableArray array];
    }
    return _allLikeArray;
}
-(NSMutableArray *)guessArray{
    if (!_guessArray) {
        _guessArray = [NSMutableArray array];
    }
    return _guessArray;
}

@end
